package com.zhinong.controller.admin;
import com.zhinong.repository.ChatHistoryRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.time.Duration;

@RequiredArgsConstructor
@RestController
@RequestMapping("/ai")
public class ChatController {
    //
//
    private final ChatClient chatClient;

    private final ChatHistoryRepository chatHistoryRepository;

    @RequestMapping(value = "/chat",produces = "text/html;charset=utf-8")
    public Flux<String> chat(String prompt, String chatId) {

        chatHistoryRepository.save("chat",chatId);
        return chatClient.prompt()
                .user(prompt)
                .advisors(a -> a.param(AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY,chatId))
                .stream()
                .content();
    }
}
//    @RequestMapping(value = "/chat", produces = "text/html;charset=utf-8")
//    public String chat(String prompt, String chatId) {
//
//        chatHistoryRepository.save("chat", chatId);
//        String result = chatClient.prompt()
//                .user(prompt)
//                .advisors(a -> a.param(AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY, chatId))
//                .stream()
//                .content()
//                .collectList()  // 收集所有字符串片段到List
//                .map(list -> String.join("", list))  // 合并List为单个字符串
//                .block(Duration.ofSeconds(30));  // 设置超时时间
//
//        return result != null ? result : "";
//    }
//}


//package com.zhinong.controller.admin;
//
//import com.zhinong.repository.ChatHistoryRepository;
//import lombok.RequiredArgsConstructor;
//import org.springframework.ai.chat.client.ChatClient;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.RestController;
//
//@RequiredArgsConstructor
//@RestController
//@RequestMapping("/ai")
//public class ChatController {
//
//    private final ChatClient chatClient;
//    private final ChatHistoryRepository chatHistoryRepository;
//
//    @RequestMapping(value = "/chat", produces = "text/html;charset=utf-8")
//    public String chat(String prompt, String chatId) {
//        chatHistoryRepository.save("chat", chatId);
//        return this.chatClient.prompt()
//                .user(prompt)
//                .call()
//                .content();
//    }
//}


